<?php

include_once 'database/connect.php';
include_once 'sympols.php';
include_once 'lib/json_decoder.php';
require_once 'mobile/index.php';
error_reporting(E_ALL);
$appId = "system";

function arrayToParams(array $arr) {
    $res = "";
    foreach ($arr as $key => $val) {
        $res.="$key=$val&";
    }
    return $res;
}

function applicationAccessed($app_id) {#1: enrollment, 2:courses, 3:quizes: 4: download
    $userId = $_GET['phone_number'];
    $query = "INSERT INTO app_usage SET app_id='$app_id', user_id='$userId'";
    $result = mysql_query($query) or die("Error executing '$query':" . mysql_error());
}

$state = $_GET['state'];
if ($state == "register") {
    extract($_GET);
    $query = "SELECT * FROM students_login WHERE phone_number='$phone_number'";
    $result = mysql_query($query) or die("Error executing '$query':" . mysql_error());
    if (mysql_num_rows($result) > 0) {
        $query = "SELECT * FROM students_login WHERE phone_number='$phone_number' and password='$password'";
        $result = mysql_query($query) or die("Error executing '$query':" . mysql_error());
        if (mysql_num_rows($result) > 0) {
            echo "success" . Sympols::$split1 . numOfNewNotifs();
        } else {
            echo "Failed: That user exists and you gave the wrong password. Please provide the correct password.";
        }
    } else {
        mysql_query("INSERT INTO students_login (username,phone_number, password) VALUES ('$username','$phone_number', '$password')");
        echo "success" . Sympols::$split1 . numOfNewNotifs();
    }
} else if ($state == "login") {
    extract($_GET);
    $query = "SELECT * FROM students_login WHERE phone_number='$phone_number' and password='$password'";
    $result = mysql_query($query) or die("Error executing '$query':" . mysql_error());
    if (mysql_num_rows($result) > 0) {
        echo "success" . Sympols::$split1 . numOfNewNotifs();
    } else {
        echo "Failed: Wrong password.";
    }
} else {
    if ($state == "enroll_home") {
        applicationAccessed(1);
    } else if ($state == "courses_home") {
        applicationAccessed(2);
    } else if ($state == "quizes_home") {
        applicationAccessed(3);
    } else if ($state == "download_home") {
        applicationAccessed(4);
    } else if ($state == "interaction_home") {
        applicationAccessed(5);
    } else if ($state == "notifications_home") {
        applicationAccessed(6);
    }
    echo jsonToWare(fetchJson());
}
?>